package com.bjb.vr.auth.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bjb.vr.auth.util.AccessRequestUtil;
import com.bjb.vr.common.dto.UmsMenu;
import com.bjb.vr.common.mapper.UmsMenuMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Objects;

/**
 * @description:
 * @author: HuJingBo
 * @time: 2022/5/14 22:08
 */
@Slf4j
@Component("rbacService")
public class RbacService {

    @Autowired
    private UmsMenuMapper umsMenuMapper;

    @Autowired
    private LoginService loginService;

    @Autowired
    private UmsAccountEnhanceService umsAccountEnhanceService;

    /**
     * 校验用户是否有权限
     * @param request
     * @return
     */
    public boolean hasPermission(HttpServletRequest request){
        // 1、如果是超级管理员，则拥有所有权限
        String username = AccessRequestUtil.getUserName();
        boolean confirm = umsAccountEnhanceService.checkSuperAdmin(null, username);
        if (confirm) {
            return true;
        }

        // 2、其他用户权限校验
        UserDetails userDetails = loginService.loadUserByUsername(username);
        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();

        // 3、封装其他用户请求的资源权限
        String requestURI = request.getRequestURI();
        LambdaQueryWrapper<UmsMenu> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(StringUtils.isNotBlank(requestURI),UmsMenu::getPath,requestURI);
        UmsMenu umsMenu = umsMenuMapper.selectOne(queryWrapper);
        if(Objects.isNull(umsMenu)){
            return false;
        }
        SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(umsMenu.getPerms());

        // 4、判断请求资源是否有权限访问
        return authorities.contains(simpleGrantedAuthority);
    }
}
